<template>
  <div id="container">
    <input
      v-model="keyword"
      id="keyword"
      placeholder="请输入搜索位置"
      autocomplete="off"
      @keyup.enter="searchPlace"
    />
    <button @click="searchPlace">搜索</button>
    <div>
      <p>经度: {{ longitude }}</p>
      <p>纬度: {{ latitude }}</p>
      <p>{{ message }}</p>
    </div>
    <div style="z-index: 999999999" v-if="places.length">
      <h3>搜索结果:</h3>
      <ul class="results">
        <li v-for="place in places" :key="place.id" @click="selectPlace(place)">
          {{ place.name }}
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
#container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 376px;
}

#keyword {
  margin-top: 1%;
  height: 30px;
  position: absolute;
  z-index: 999999;
}

/* 自定义按钮样式 */
button {
  margin-top: 10px;
  padding: 5px 10px;
}

.results {
  position: absolute;
  top: 50px; /* 根据需要调整 */
  left: 0;
  right: 0;
  z-index: 1000; /* 确保在地图之上 */
  background-color: white; /* 设定背景颜色 */
  border: 1px solid #ccc; /* 可选的边框 */
  width: 200px;
  overflow-y: scroll;
}
</style>

<script setup>
import { ref, onMounted, defineProps, watch } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps({
  message: String
})

const keyword = ref('')
const longitude = ref(null)
const latitude = ref(null)
const places = ref([]) // 存储搜索结果
const emit = defineEmits(['update:longitude', 'update:latitude', 'update:address', 'childEvent'])
let map
let marker // 定义标记变量

const initMap = () => {
  AMapLoader.load({
    key: 'be64c3933f21b1cf456735c678152f48',
    version: '1.4.15',
    plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder']
  })
    .then((AMap) => {
      map = new AMap.Map('container', {
        resizeEnable: true,
        zoom: 10,
        center: [116.397428, 39.90923]
      })
      emit('childEvent', 'Hello from Child!')

      AMap.plugin('AMap.ControlBar', function () {
        const controlBar = new AMap.ControlBar({
          showZoomBar: true, // 显示缩放条
          showControlButton: true // 显示控制按钮
        })
        map.addControl(controlBar)
      })

      let marker; // 声明一个标记变量
      map.on('click', async (e) => {
        longitude.value = e.lnglat.lng
        latitude.value = e.lnglat.lat
        emit('longitudeLi', longitude.value)
        emit('latitudeLi', latitude.value)

        const apiKey = 'be64c3933f21b1cf456735c678152f48'
        const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude.value},${latitude.value}`
        try {
          const response = await fetch(url)
          const data = await response.json()

          if (data.status === '1') {
            const address = data.regeocode.formatted_address
             if (marker) {
                marker.setMap(null); // 从地图上移除旧标记
            }

            // 创建新标记
            marker = new AMap.Marker({
                position: [longitude.value, latitude.value],
                title: address,
            });
            marker.setMap(map); // 将新标记添加到地图上

            emit('addressLi', address)
          }
        } catch (error) {
          console.error('请求错误:', error)
        }
      })
    })
    .catch((error) => {
      console.error('加载 AMap 失败:', error)
    })
}

// 搜索地点
const searchPlace = async () => {
  const apiKey = 'be64c3933f21b1cf456735c678152f48'
  const url = `https://restapi.amap.com/v3/place/text?keywords=${encodeURIComponent(
    keyword.value
  )}&key=${apiKey}&extensions=all`

  try {
    const response = await fetch(url)
    const data = await response.json()
    if (data.status === '1') {
      places.value = data.pois // 存储搜索结果
    } else {
      console.error('搜索失败:', data.info)
      places.value = []
    }
  } catch (error) {
    console.error('请求错误:', error)
  }
}

const selectPlace = (place) => {
  longitude.value = place.location.split(',')[0]
  latitude.value = place.location.split(',')[1]
  emit('longitudeLi', longitude.value)
  emit('latitudeLi', latitude.value)

  // 清空搜索框内容
  keyword.value = ''

  // 在地图上添加标记
  if (marker) {
    marker.setMap(null) // 如果已存在标记，则移除
  }

  marker = new AMap.Marker({
    position: [longitude.value, latitude.value], // 设置标记的位置
    title: place.name // 设置标记的标题
  })

  marker.setMap(map) // 将标记添加到地图上

  console.log(`选择地点: ${place.name}, 经度: ${longitude.value}, 纬度: ${latitude.value}`)
}

watch(keyword, (newVal) => {
  if (!newVal) {
    places.value = [] // 清空搜索结果
  }
})
// 在组件挂载后初始化地图
const zoomIn = () => {
  map.setZoom(map.getZoom() + 1)
}

const zoomOut = () => {
  map.setZoom(map.getZoom() - 1)
}
onMounted(initMap)
</script> 